package com.zoffy.catdiarybackend.controller;

import com.zoffy.catdiarybackend.service.AssetsService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import java.io.IOException;

@RestController
@RequestMapping("/assets")
public class AssetsController {
    @Resource
    private AssetsService assetsService;

    @RequestMapping (value = "/**",produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] getResource(HttpServletRequest request) throws IOException {
        AntPathMatcher antPathMatcher=new AntPathMatcher();
        String uri = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        // 获取映射的路径
        String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        String resourcePath = antPathMatcher.extractPathWithinPattern( pattern,uri);
        return assetsService.getResource(resourcePath);
    }
}
